<?php

namespace plugin\ycMassage\app\admin\controller;

use app\common\builder\ListBuilder;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageRegions;
use plugin\ycMassage\app\model\MassageRegionsAlias;
use support\Request;
use think\facade\Cache;
use think\facade\Db;
use plugin\ycMassage\api\Install;

class RegionsController extends BaseController
{

    /**
     * 获取菜单表格
     * @param \support\Request $request
     * @return mixed
     * @author John
     */
    public function indexGetTable(Request $request)
    {
        $builder = new ListBuilder;
        $builder->addActionOptions('操作', [
            'width' => 120
        ]);
        $builder->addTopButton('cache', '缓存', [
            'api'    => $this->pluginPrefix . '/admin/Regions/cache',
            'type'      => 'confirm',
            'method' => 'delete',
        ], [
            'type' => 'success',
            'title'   => '温馨提示',
            'content' => '点击确定立即更新缓存',
        ], [
            'type' => 'success',
        ]);
        $builder->addTopButton('reset', '重新导入', [
            'api'    => $this->pluginPrefix . '/admin/Regions/reset',
            'type'      => 'confirm',
            'method' => 'delete',
        ], [
            'type' => 'danger',
            'title'   => '温馨提示',
            'content' => '点击确定重新导入',
        ], [
            'type' => 'danger',
        ]);
        $builder->addRightButton('children', '子级', [
            'api'    => $this->pluginPrefix . '/admin/Regions/index',
            'path' => '/Regions/index',
            'aliasParams' => [
                'id' => 'pid'
            ],
            'params' => [
                'field' => 'level',
                'where' => 'in',
                'value' => [0, 1, 2]
            ]
        ], [], [
            'type' => 'primary',
            'link' => true
        ]);
        $data    = $builder
            ->addColumn('id', 'ID', [
                'width' => 160
            ])
            ->addColumn('title', '地区名称')
            ->addColumnEle('level', '行政等级', [
                'width' => 120,
                'params' => [
                    'type' => 'tags',
                    'options' => [
                        0 => '省级',
                        1 => '市级',
                        2 => '区级',
                        3 => '街道',
                    ],
                    'style' => [
                        0 => [
                            'type' => 'success',
                        ],
                        1 => [
                            'type' => '',
                        ],
                        2 => [
                            'type' => 'warning',
                        ],
                        3 => [
                            'type' => 'danger',
                        ],
                    ]
                ],
            ])
            ->addColumnEle('state', '状态', [
                'width' => 120,
                'params' => [
                    'type' => 'switch',
                    'api' => $this->pluginPrefix . '/admin/Regions/updateState',
                    'checked' => [
                        'text' => '可用',
                        'value' => 1
                    ],
                    'unchecked' => [
                        'text' => '不可用',
                        'value' => 0
                    ]
                ],
            ])
            ->create();
        return $this->successRes($data);
    }

    /**
     * 获取列表
     * @param \support\Request $request
     * @return mixed
     * @author John
     */
    public function index(Request $request)
    {
        $saas_appid = $request->saas_appid;
        $pid = $request->get('pid');
        $where = [['r.pid', '=', NULL]];
        if ($pid) {
            $where = [['r.pid', '=', $pid]];
        }
        $data = MassageRegions::alias('r')->where($where)
            ->join('massage_regions_alias alias', 'alias.regions_id=r.id AND alias.saas_appid = ' . $saas_appid, 'LEFT')
            ->field('r.*,alias.regions_id as alias_id')->select()->each(function ($item) {
                if ($item->alias_id) {
                    $item->state = 1;
                }
            });
        return $this->successRes($data);
    }

    public function updateState(Request $request)
    {
        $id = $request->post('id');
        $saas_appid = $request->saas_appid;
        Db::startTrans();
        try {
            $MassageRegions = MassageRegions::where(['id' => $id])->find();
            $cacheKey = 'massage_regions.ids.' . $MassageRegions->id;
            $Alias = MassageRegionsAlias::where(['saas_appid' => $saas_appid, 'regions_id' => $id])->find();
            $createAppendIds = [];
            $ids = [];
            switch ($MassageRegions->level) {
                case 0:
                    $ids = Cache::get($cacheKey);
                    if (!$ids) {
                        $ids = MassageRegions::where(['province_id' => $MassageRegions->id])->column('id');
                        Cache::set($cacheKey, $ids);
                    }
                    break;
                case 1:
                    $ids = Cache::get($cacheKey);
                    if (!$ids) {
                        $ids = MassageRegions::where(['city_id' => $MassageRegions->id])->column('id');
                        Cache::set($cacheKey, $ids);
                    }
                    $createAppendIds[] = $MassageRegions->province_id;
                    break;
                case 2:
                    $ids = Cache::get($cacheKey);
                    if (!$ids) {
                        $ids = MassageRegions::where(['area_id' => $MassageRegions->id])->column('id');
                        Cache::set($cacheKey, $ids);
                    }
                    $createAppendIds[] = $MassageRegions->province_id;
                    $createAppendIds[] = $MassageRegions->city_id;
                    break;
                case 3:
                    $createAppendIds[] = $MassageRegions->province_id;
                    $createAppendIds[] = $MassageRegions->city_id;
                    $createAppendIds[] = $MassageRegions->area_id;
                    break;
            }
            $ids[] = $MassageRegions->id;
            if ($Alias) {
                MassageRegionsAlias::where(['saas_appid' => $saas_appid])->whereIn('regions_id', $ids)->delete();
            } else {
                $sdata = [];
                foreach ($ids as $key => $value) {
                    $sdata[] = ['saas_appid' => $saas_appid, 'regions_id' => $value];
                }
                $MassageRegionsAlias = new MassageRegionsAlias;
                $MassageRegionsAlias->saveAll($sdata);
                foreach ($createAppendIds as $key => $value) {
                    $MassageRegionsAlias = MassageRegionsAlias::where(['saas_appid' => $saas_appid, 'regions_id' => $value])->find();
                    if (!$MassageRegionsAlias) {
                        $MassageRegionsAlias = new MassageRegionsAlias;
                        $MassageRegionsAlias->saas_appid = $saas_appid;
                        $MassageRegionsAlias->regions_id = $value;
                        $MassageRegionsAlias->save();
                    }
                }
            }
            Db::commit();
            return $this->success('修改成功');
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail($th->getMessage());
        }
    }
    public function cache(Request $request)
    {
        $saas_appid = $request->saas_appid;

        $data = MassageRegions::alias('r')
            ->join('massage_regions_alias alias', 'alias.regions_id=r.id AND alias.saas_appid = ' . $saas_appid)
            ->field('r.*')
            ->select()->toArray();
        if (empty($data)) {
            $data = MassageRegions::select()->toArray();
        }
        # 将state为0和子级的数据过滤掉
        $organized = MassageRegions::organizeRecords($data);
        $data = MassageRegions::buildTree($organized);
        MassageRegions::cacheCascaderOptions($data, $saas_appid);
        return $this->success('更新成功');
    }
    public function reset(Request $request)
    {
        Install::installRegions();
        return $this->success('导入成功');
    }
}
